package smashedapples.google.googleapi
{
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.google.accounts.GoogleAuthRequest;
	import smashedapples.google.accounts.GoogleAuthResponse;
	import smashedapples.utils.StringUtils;
	
	[Event( name="authenticated",type="AppEvent") ]
	
	public class BaseGoogleDataApi extends NonVisualComponent
	{
		protected var authToken:String;
		
		public function isAuthenticated():Boolean
		{
			if( authToken == null )
				return false;
			return true;
		}
		
		public function getAuthTokenHeaderValue():String
		{
			return "GoogleLogin auth=" + StringUtils.trim( this.authToken );
		}
		
		private var $service:String;
		public function get service():String
		{
			return this.$service;
		}
		
		public function set service( value:String ):void
		{
			this.$service = value;
		}
		
		private var $email:String;
		public function get email():String
		{
			return this.$email;
		}
		
		public function set email( value:String ):void
		{
			this.$email = value;
		}
		
		private var $password:String;
		public function get password():String
		{
			return this.$password;
		}
		
		public function set password( value:String ):void
		{
			this.$password = value;
		}
		
		private var $source:String;
		public function get source():String
		{
			return this.$source;
		}
		
		public function set source( value:String ):void
		{
			this.$source = value;
		}
		
		
		public function authenticate( email:String, password:String, source:String ):AsyncToken
		{
			this.email = email;
			this.password = password;
			this.source = source;
			
			var request:GoogleAuthRequest = new GoogleAuthRequest( this.email, this.password, this.service, this.source, this.handleAuthResponse );
			return request.send();	
		}
		
		private function handleAuthResponse( response:GoogleAuthResponse ):void
		{
			this.authToken = response.authToken;
			
			this.dispatchEvent( new AppEvent( "authenticated" ) );
		}
		
		
		protected function getHttpService( url:String, result:Function, fault:Function = null ):HTTPService
		{
			fault = fault || defaultFaultHandler;
			
			var service:HTTPService = new HTTPService();
				service.url = url;
				service.headers = { Authorization: this.getAuthTokenHeaderValue() };
				service.addEventListener(ResultEvent.RESULT, result );
				service.addEventListener(FaultEvent.FAULT, fault);
		
			return service;
		}
		
		protected function defaultFaultHandler( event:FaultEvent ):void
		{
			trace(event.fault);
		}
		

	}
}